package com.qujia.station.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qujia.common.constant.UserConstants;
import com.qujia.common.core.domain.AjaxResult;
import com.qujia.common.core.domain.entity.SysRole;
import com.qujia.common.core.domain.entity.SysUser;
import com.qujia.common.core.domain.model.LoginUser;
import com.qujia.common.exception.BaseException;
import com.qujia.common.exception.CustomException;
import com.qujia.common.utils.SecurityUtils;
import com.qujia.station.domain.*;
import com.qujia.station.domain.dto.AddStationSettleInfoDto;
import com.qujia.station.domain.dto.MemberManagementQueryDto;
import com.qujia.station.domain.vo.*;
import com.qujia.station.mapper.MemberManagementMapper;
import com.qujia.station.mapper.StationEnterpriseCopMapper;
import com.qujia.station.mapper.StationMapper;
import com.qujia.station.mapper.StationOillGunMapper;
import com.qujia.station.service.IEnterpriseService;
import com.qujia.station.service.IStationService;
import com.qujia.station.service.MemberManagementService;
import com.qujia.station.service.TeamManagementService;
import com.qujia.system.mapper.SysUserMapper;
import com.qujia.system.service.ISysRoleService;
import com.qujia.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 油站信息Service业务层处理
 *
 * @author qujia
 * @date 2020-12-08
 */
@Service
@Slf4j
public class StationServiceImpl extends ServiceImpl<StationMapper, Station> implements IStationService {
    @Autowired
    private StationMapper stationMapper;

    @Autowired
    private IStationService stationService;

    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private MemberManagementMapper managementMapper;
    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private StationEnterpriseCopMapper stationEnterpriseCopMapper;

    @Autowired
    private TeamManagementService teamManagementService;

    @Autowired
    private MemberManagementService memberManagementService;

    @Autowired
    private StationOillGunMapper stationOillGunMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private IEnterpriseService enterpriseService;

    /**
     * 查询油站信息
     *
     * @param stationId 油站信息ID
     * @return 油企信息
     */
    public Station selectStationById(Long stationId) {
        return stationMapper.selectStationById(stationId);
    }

    @Override
    public List<Station> getStationByEnterpriseId(Long enterpriseId) {
        return stationMapper.getStationByEnterpriseId(enterpriseId);
    }

    public Station selectStationByName(String stationName) {
        return stationMapper.selectStationByName(stationName);
    }

    @Override
    public void addStationSettleInfo(AddStationSettleInfoDto addStationSettleInfoDto) {
        stationMapper.updateStationSettleInfo(addStationSettleInfoDto);
    }

    @Override
    public AddStationSettleInfoDto getStationSettleInfo(String stationId) {
        Long stationIdLong;
        try {
            stationIdLong = Long.valueOf(stationId);
        } catch (Exception e) {
            throw new CustomException("油站id格式错误");
        }
        return stationMapper.getStationSettleInfo(stationIdLong);
    }

    @Override
    public int setShowCommisson(Station station) {

        return stationMapper.setShowCommisson(station);
    }

    @Override
    public int setOpenStaffClass(Station station) {

        return stationMapper.setOpenStaffClass(station);
    }

    @Override
    public int setShowPaymentCommission(Station station) {
        if (Objects.nonNull(station) && Objects.nonNull(station.getPhysicalCardAmount())) {
            if (station.getPhysicalCardAmount().compareTo(BigDecimal.ZERO) < 0) {
                throw new BaseException("实体卡消费额度下限不能小于0");
            }
            if (station.getPhysicalCardAmount().toString().length() > 13) {
                throw new BaseException("实体卡消费额度下限太大");
            }
        }
        return stationMapper.setShowPaymentCommission(station);
    }


    @Override
    public List<StationByEnterpriseVo> getStationByEnterprise(Long enterpriseId) {

        ArrayList<StationByEnterpriseVo> stationByEnterpriseVos = new ArrayList<>();

        LoginUser current = SecurityUtils.getLoginUser();
        SysUser user = current.getUser();

        if (enterpriseId != null) {
            Station station = new Station();
            station.setEnterpriseId(enterpriseId);
            station.setDeleteStatus("0");
            List<Station> stations = stationMapper.selectStationList(station);
            for (Station stationInfo : stations) {
                StationByEnterpriseVo stationByEnterpriseVo = new StationByEnterpriseVo();
                BeanUtil.copyProperties(stationInfo, stationByEnterpriseVo);
                stationByEnterpriseVos.add(stationByEnterpriseVo);
            }
            return stationByEnterpriseVos;
        }


        if (UserConstants.LEVEL_TWO.equals(user.getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(user.getEnterpriseId());
            station.setDeleteStatus("0");

            List<Station> stations = stationMapper.selectStationList(station);
            for (Station stationInfo : stations) {
                StationByEnterpriseVo stationByEnterpriseVo = new StationByEnterpriseVo();
                BeanUtil.copyProperties(stationInfo, stationByEnterpriseVo);
                stationByEnterpriseVos.add(stationByEnterpriseVo);
            }
            return stationByEnterpriseVos;
        }
        if (UserConstants.LEVEL_THREE.equals(user.getUserLevel())) {
            Station station = new Station();
            station.setStationId(user.getStationId());
            station.setDeleteStatus("0");
            List<Station> stations = stationMapper.selectStationList(station);
            if (CollectionUtil.isNotEmpty(stations)) {
                StationByEnterpriseVo stationByEnterpriseVo = new StationByEnterpriseVo();
                BeanUtil.copyProperties(stations.get(0), stationByEnterpriseVo);
                stationByEnterpriseVos.add(stationByEnterpriseVo);
            }
            return stationByEnterpriseVos;
        }
        if (UserConstants.LEVEL_FIVE.equals(user.getUserLevel())) {
            List<Long> managerEnterpriseId = teamManagementService.getManagerEnterpriseId(user.getUserId());
            if (CollectionUtil.isNotEmpty(managerEnterpriseId)) {
                for (Long enId : managerEnterpriseId) {
                    Station station = new Station();
                    station.setEnterpriseId(enId);
                    station.setDeleteStatus("0");

                    List<Station> stations = stationMapper.selectStationList(station);
                    for (Station stationInfo : stations) {
                        StationByEnterpriseVo stationByEnterpriseVo = new StationByEnterpriseVo();
                        BeanUtil.copyProperties(stationInfo, stationByEnterpriseVo);
                        stationByEnterpriseVos.add(stationByEnterpriseVo);
                    }
                }
            }
            return stationByEnterpriseVos;
        }

        if (UserConstants.LEVEL_SIX.equals(user.getUserLevel())) {
            List<Long> managerEnterpriseId = memberManagementService.getMemberEnterpriseId(user.getUserId());
            if (CollectionUtil.isNotEmpty(managerEnterpriseId)) {
                for (Long enId : managerEnterpriseId) {
                    Station station = new Station();
                    station.setEnterpriseId(enId);
                    station.setDeleteStatus("0");

                    List<Station> stations = stationMapper.selectStationList(station);
                    for (Station stationInfo : stations) {
                        StationByEnterpriseVo stationByEnterpriseVo = new StationByEnterpriseVo();
                        BeanUtil.copyProperties(stationInfo, stationByEnterpriseVo);
                        stationByEnterpriseVos.add(stationByEnterpriseVo);
                    }
                }
                return stationByEnterpriseVos;
            }
        }
        if (UserConstants.LEVEL_SEVEN.equals(user.getUserLevel())) {

                LoginUser currentUser = SecurityUtils.getLoginUser();
                EnterpriseAndStationVo itemIds = stationService.getItemIds(currentUser.getUser());
                List<Long> enterpriseIds = itemIds.getEnterpriseIds();
                if (enterpriseIds != null && enterpriseIds.size()>0) {
                    List<Station> stations = stationMapper.selectStationListByPageEnterpriseIds(enterpriseIds);
                    for (Station stationInfo : stations) {
                        StationByEnterpriseVo stationByEnterpriseVo = new StationByEnterpriseVo();
                        BeanUtil.copyProperties(stationInfo, stationByEnterpriseVo);
                        stationByEnterpriseVos.add(stationByEnterpriseVo);
                    }
                    return stationByEnterpriseVos;
                } else {
                    throw new CustomException(UserConstants.NO_ENTERPRISE);
                }


        }
        if (UserConstants.LEVEL_ONE.equals(user.getUserLevel()) || StringUtils.isBlank(user.getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(enterpriseId);
            station.setDeleteStatus("0");

            List<Station> stations = stationMapper.selectStationList(station);
            if (CollectionUtil.isNotEmpty(stations)) {
                for (Station stationInfo : stations) {
                    StationByEnterpriseVo stationByEnterpriseVo = new StationByEnterpriseVo();
                    BeanUtil.copyProperties(stationInfo, stationByEnterpriseVo);
                    stationByEnterpriseVos.add(stationByEnterpriseVo);
                }
                return stationByEnterpriseVos;
            }

        }

        return stationByEnterpriseVos;
    }

    @Override
    public List<StationByEnterpriseVo> getStationInfo() {
        ArrayList<StationByEnterpriseVo> stationByEnterpriseVos = new ArrayList<>();
        //获取用户信息
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if (sysUser.getUserLevel().equals("1")) {
            Long enterpriseId = sysUser.getEnterpriseId();
            Station station = new Station();
            station.setEnterpriseId(enterpriseId);
            station.setStatus("1");
            station.setDeleteStatus("0");
            List<Station> stations = stationMapper.selectStationList(station);
            if (CollectionUtil.isNotEmpty(stations)) {
                for (Station station1 : stations) {
                    Long stationId = station1.getStationId();
                    String stationName = station1.getStationName();
                    StationByEnterpriseVo stationByEnterpriseVo = new StationByEnterpriseVo();
                    stationByEnterpriseVo.setStationId(stationId);
                    stationByEnterpriseVo.setStationName(stationName);
                    stationByEnterpriseVos.add(stationByEnterpriseVo);
                }
                return stationByEnterpriseVos;
            }
        } else if (sysUser.getUserLevel().equals("2")) {
            Station station = stationMapper.selectStationById(sysUser.getStationId());
            if (Objects.nonNull(station)) {
                if (!station.getStatus().equals("1") || !station.getDeleteStatus().equals("0")) {
                    return stationByEnterpriseVos;
                }
                String stationName = station.getStationName();
                Long stationId = station.getStationId();
                StationByEnterpriseVo stationByEnterpriseVo = new StationByEnterpriseVo();
                stationByEnterpriseVo.setStationId(stationId);
                stationByEnterpriseVo.setStationName(stationName);
                stationByEnterpriseVos.add(stationByEnterpriseVo);
                return stationByEnterpriseVos;
            }
        }
        return null;
    }

    @Override
    public List<Long> getStationByEnterpriseList(List<Long> enterpriseId) {

        return stationMapper.selectStationListByEnterpriseIds(enterpriseId);
    }

    @Override
    public List<Long> getStationIdList(Station station) {
        return stationMapper.getStationIdList(station);
    }

    @Override
    public List<Station> selectStationListByEnterpriseId(Long enterpriseId) {
        return stationMapper.selectStationListByEnterpriseId(enterpriseId);
    }

    @Override
    @Transactional
    public int logicallyDelete(Long stationId) {
        int i = 0;
        LoginUser currentUser = SecurityUtils.getLoginUser();
        //防止修改其他参数
        Station station1 = new Station();
        station1.setStationId(stationId);
        station1.setDeleteDate(new Date());
        station1.setDeleteStatus("1");
        station1.setDeleteUser(currentUser.getUser().getUserId());
        i = i + updateStation(station1);
        //逻辑删除油站的油品油枪
        StationOillGun stationOillGun = new StationOillGun();
        stationOillGun.setStationId(stationId);
        stationOillGun.setDeleteUser(currentUser.getUser().getUserId());
        stationOillGun.setDeleteStatus("1");
        stationOillGun.setDeleteDate(new Date());
        i = i + stationOillGunMapper.updateStationOillGunByStationId(stationOillGun);
        //删除油站员工
        SysUser sysUser = new SysUser();
        sysUser.setStationId(stationId);
        sysUser.setDelFlag("2");//数据库字段描述2代表删除
        i = i + sysUserMapper.updateByStationId(sysUser);
        return i;
    }

    @Override
    public EnterpriseAndStationVo getItemIds(SysUser sysUser) {
        EnterpriseAndStationVo item = new EnterpriseAndStationVo();
        item.setUserList(new ArrayList<>());
        List<Enterprise> enterpriseList = new ArrayList<>();
        List<Station> stationList = new ArrayList<>();
        //区域经理
        if (StringUtils.equals(UserConstants.LEVEL_FIVE, sysUser.getUserLevel())) {
            //查询团队
            TeamManagement one =
                    teamManagementService.getOne(new QueryWrapper<TeamManagement>().eq("leader_id", sysUser.getUserId()).eq("status",0));
            List<String> strings = null;
            if (one != null ) {
                List<String> enterpriseIds = new ArrayList<>();
                String members = one.getMembers();

                if(members != null && !members.isEmpty()){
                    strings = Arrays.asList(one.getMembers().split(","));
                }else{
                    throw new BaseException("未创建油企");
                }
                SysUser user = new SysUser();
                user.setUserIdList(strings.stream().map(Long::parseLong).collect(Collectors.toList()));
                List<SysUser> sysUsers = sysUserService.selectUserList(user);
                if (sysUsers.size()>0) {
                    for(SysUser sysUserItem:sysUsers){
                        MemberManagementQueryDto memberManagementDto = new MemberManagementQueryDto();
                        memberManagementDto.setSalesmanId(sysUserItem.getUserId());
                        memberManagementDto.setStatus(0);
                        List<MemberManagementVo> aMemberManagementQueryDto =    managementMapper.selectMemberList(memberManagementDto);
                    for(MemberManagementVo aMemberManagementVo:aMemberManagementQueryDto){
                        if(aMemberManagementVo.getEnterpriseIds()!=null){
                            List<String> strings1 = Arrays.asList(aMemberManagementVo.getEnterpriseIds().split(","));
                            enterpriseIds.addAll(strings1);
                        }
                    }

                    }
                }
                //查询成员
                List<MemberManagement> managements =
                        memberManagementService.list(new QueryWrapper<MemberManagement>()
                                .in("salesman_id", strings));
                //查询油企
                if (managements != null && managements.size()>0) {
                    List<String> collect =
                            managements.stream().map(MemberManagement::getEnterpriseId).collect(Collectors.toList());
                    for (String s : collect) {
                        List<String> strings1 = Arrays.asList(s.split(","));
                        enterpriseIds.addAll(strings1);
                    }
                }else{
                    throw new BaseException("未创建油企");
                }
                enterpriseList = enterpriseService.list(new QueryWrapper<Enterprise>()
                        .in("enterprise_id", enterpriseIds)
                        .eq("delete_status", "0"));
            }else{
                throw new BaseException("未创建油企");
            }
        }
        //业务员
        if (StringUtils.equals(UserConstants.LEVEL_SIX, sysUser.getUserLevel())) {


            MemberManagement managements =
                    memberManagementService.getOne(new QueryWrapper<MemberManagement>().eq("salesman_id", sysUser.getUserId()));
            if (managements != null&&managements.getEnterpriseId()!=null) {
              List<String> strings1 = Arrays.asList(managements.getEnterpriseId().split(","));

                enterpriseList =
                        enterpriseService.list(new QueryWrapper<Enterprise>()
                                .in("enterprise_id", strings1)
                                .eq("delete_status", "0"));
            }else{
                throw new BaseException("未创建油企");
            }
        }
        //合伙人
        if (StringUtils.equals(UserConstants.LEVEL_SEVEN, sysUser.getUserLevel())) {
            SysUser user = new SysUser();
            user.setSupremeLevelId(sysUser.getUserId());
            List<SysUser> sysUsers = userMapper.selectUserListBySupremeLevel(user);
            if (sysUsers.size()>0) {
                List<Long> collect = sysUsers.stream().map(SysUser::getEnterpriseId).collect(Collectors.toList());
                enterpriseList = enterpriseService.list(new QueryWrapper<Enterprise>()
                        .in("enterprise_id", collect)
                        .eq("delete_status", "0"));
                if (enterpriseList.size()>0) {
                    List<Long> collect1 = enterpriseList.stream().map(Enterprise::getEnterpriseId).collect(Collectors.toList());
                    stationList.addAll(stationService.list(new QueryWrapper<Station>().in("enterprise_id", collect1)));
                }else{
                    throw new BaseException("未创建油企");
                }
                List<Long> collect1 = sysUsers.stream().map(SysUser::getStationId).collect(Collectors.toList());
                List<Station> stations = stationService.list(new QueryWrapper<Station>().in("enterprise_id", collect1));
                stationList.addAll(stations);
            }else{
                throw new BaseException("未创建油企");
            }

        }
        if (enterpriseList != null && enterpriseList.size() > 0) {
            List<Long> enterpriseIds = enterpriseList.stream().map(Enterprise::getEnterpriseId).collect(Collectors.toList());
            stationList.addAll(stationService.list(new QueryWrapper<Station>().in("enterprise_id", enterpriseIds)));
            List<Long> stationIds = stationList.stream().map(Station::getStationId).collect(Collectors.toList());
            if(stationIds==null||stationIds.size()==0){
                throw new BaseException("未创建油站");
            }
            item.setStationIds(stationIds);
            item.setEnterpriseIds(enterpriseIds);
            List<String> collect = stationIds.stream().map(String::valueOf).collect(Collectors.toList());
            item.setStationIdsStr(collect);
        }else{
            throw new BaseException("未创建油企");
        }
        return item;
    }



    @Override
    public EnterpriseAndStationVo getItemIdsByAuthor(SysUser sysUser) {
        EnterpriseAndStationVo item = new EnterpriseAndStationVo();
        item.setUserList(new ArrayList<>());
        List<Enterprise> enterpriseList = new ArrayList<>();
        List<Station> stationList = new ArrayList<>();
        //区域经理
        if (StringUtils.equals(UserConstants.LEVEL_FIVE, sysUser.getUserLevel())) {
            //查询团队
            TeamManagement one =
                    teamManagementService.getOne(new QueryWrapper<TeamManagement>().eq("leader_id", sysUser.getUserId()).eq("status",0));
            List<String> strings = null;
            if (one != null ) {
                List<String> enterpriseIds = new ArrayList<>();
                String members = one.getMembers();

                if(members != null && !members.isEmpty()){
                    strings = Arrays.asList(one.getMembers().split(","));
                }else{
                    throw new BaseException("未创建油企");
                }
                SysUser user = new SysUser();
                user.setUserIdList(strings.stream().map(Long::parseLong).collect(Collectors.toList()));
                List<SysUser> sysUsers = sysUserService.selectUserList(user);
                if (sysUsers.size()>0) {
                    for(SysUser sysUserItem:sysUsers){
                        MemberManagementQueryDto memberManagementDto = new MemberManagementQueryDto();
                        memberManagementDto.setSalesmanId(sysUserItem.getUserId());
                        memberManagementDto.setStatus(0);
                        List<MemberManagementVo> aMemberManagementQueryDto =    managementMapper.selectMemberList(memberManagementDto);
                        for(MemberManagementVo aMemberManagementVo:aMemberManagementQueryDto){
                            if(aMemberManagementVo.getEnterpriseIds()!=null){
                                List<String> strings1 = Arrays.asList(aMemberManagementVo.getEnterpriseIds().split(","));
                                enterpriseIds.addAll(strings1);
                            }
                        }

                    }
                }
                //查询成员
                List<MemberManagement> managements =
                        memberManagementService.list(new QueryWrapper<MemberManagement>()
                                .in("salesman_id", strings));
                //查询油企
                if (managements != null && managements.size()>0) {
                    List<String> collect =
                            managements.stream().map(MemberManagement::getEnterpriseId).collect(Collectors.toList());
                    for (String s : collect) {
                        List<String> strings1 = Arrays.asList(s.split(","));
                        enterpriseIds.addAll(strings1);
                    }
                }else{
                    throw new BaseException("未创建油企");
                }
                enterpriseList = enterpriseService.list(new QueryWrapper<Enterprise>()
                        .in("enterprise_id", enterpriseIds)
                        .eq("delete_status", "0"));
            }else{
                throw new BaseException("未创建油企");
            }
        }
        //业务员
        if (StringUtils.equals(UserConstants.LEVEL_SIX, sysUser.getUserLevel())) {


            MemberManagement managements =
                    memberManagementService.getOne(new QueryWrapper<MemberManagement>().eq("salesman_id", sysUser.getUserId()));
            if (managements != null&&managements.getEnterpriseId()!=null) {
                List<String> strings1 = Arrays.asList(managements.getEnterpriseId().split(","));

                enterpriseList =
                        enterpriseService.list(new QueryWrapper<Enterprise>()
                                .in("enterprise_id", strings1)
                                .eq("delete_status", "0"));
            }else{
                throw new BaseException("未创建油企");
            }
        }
        //合伙人
        if (StringUtils.equals(UserConstants.LEVEL_SEVEN, sysUser.getUserLevel())) {
            SysUser user = new SysUser();
            user.setSupremeLevelId(sysUser.getUserId());
            List<SysUser> sysUsers = userMapper.selectUserListBySupremeLevel(user);
            if (sysUsers.size()>0) {
                List<Long> collect = sysUsers.stream().map(SysUser::getEnterpriseId).collect(Collectors.toList());
                enterpriseList = enterpriseService.list(new QueryWrapper<Enterprise>()
                        .in("enterprise_id", collect)
                        .eq("delete_status", "0"));
                if (enterpriseList.size()>0) {
                    List<Long> collect1 = enterpriseList.stream().map(Enterprise::getEnterpriseId).collect(Collectors.toList());
                    stationList.addAll(stationService.list(new QueryWrapper<Station>().in("enterprise_id", collect1)));
                }else{
                    throw new BaseException("未创建油企");
                }
                List<Long> collect1 = sysUsers.stream().map(SysUser::getStationId).collect(Collectors.toList());
                List<Station> stations = stationService.list(new QueryWrapper<Station>().in("enterprise_id", collect1));
                stationList.addAll(stations);
            }else{
                throw new BaseException("未创建油企");
            }

        }
        if (enterpriseList != null && enterpriseList.size() > 0) {
            List<Long> enterpriseIds = enterpriseList.stream().map(Enterprise::getEnterpriseId).collect(Collectors.toList());
            stationList.addAll(stationService.list(new QueryWrapper<Station>().in("enterprise_id", enterpriseIds)));
            List<Long> stationIds = stationList.stream().map(Station::getStationId).collect(Collectors.toList());
            item.setStationIds(stationIds);
            item.setEnterpriseIds(enterpriseIds);
            List<String> collect = stationIds.stream().map(String::valueOf).collect(Collectors.toList());
            item.setStationIdsStr(collect);
        }else{
            throw new BaseException("未创建油企");
        }
        return item;
    }
    /**
     * 查询油站信息列表
     *
     * @param station 油站信息
     * @return 油站信息集合
     */
    public List<Station> transactionStationList(Station station) {
        return stationMapper.transactionStationList(station);

    }

    /**
     * 查询油站信息列表
     *
     * @param station 油站信息
     * @return 油站信息集合
     */
    public List<Station> selectStationList(Station station) {
        return stationMapper.selectStationList(station);

    }

    /**
     * 新增油站信息
     *
     * @param station 油站信息
     * @return 结果
     */
    public int insertStation(Station station) {
        return stationMapper.insertStation(station);
    }

    @Transactional
    public AjaxResult addStation(StationVo stationVo) {
        StationEnterpriseCopInfo stationEnterpriseCopInfo = new StationEnterpriseCopInfo();
        stationEnterpriseCopInfo.setCopId(stationVo.getCopId());
        stationEnterpriseCopInfo.setType(2);
        StationEnterpriseCopInfo copIdRes = stationEnterpriseCopMapper.selectByCopId(stationEnterpriseCopInfo);
        if (Objects.nonNull(copIdRes)) {
            Station station = new Station();
            station.setStationId(copIdRes.getStationId());
            station.setStationName(stationVo.getStationName());
            Station stationRes = stationMapper.selectStationById(copIdRes.getStationId());
            stationMapper.updateStation(station);
            return AjaxResult.success("更新油站成功", stationRes.getStationCode());
        }


        Calendar cal = Calendar.getInstance();
        int m = 0;
        Random random = new Random();
        String result1 = "";
        for (int i = 0; i < 4; i++) {
            result1 += random.nextInt(10);
        }
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1;
        int yearcount = year - 2000;
        String code = "S" + yearcount + month + "0001" + result1;
        Station station = new Station();
        station.setEnterpriseId(stationVo.getEnterpriseId());
        station.setStationCode(code);
        station.setStatus(stationVo.getStatus());
        station.setStationName(stationVo.getStationName());
        m = stationMapper.insertStation(station);
        if (m <= 0) {
            return AjaxResult.error("新增失败");
        }

        stationEnterpriseCopInfo.setType(2);
        stationEnterpriseCopInfo.setStationId(station.getStationId());
        stationEnterpriseCopInfo.setEnterpriseId(stationVo.getEnterpriseId());
        Integer res = stationEnterpriseCopMapper.insertInfo(stationEnterpriseCopInfo);
        if (res <= 0) {
            return AjaxResult.error("新增失败");
        }

        Long[] roles = {Long.parseLong(19 + "")};
        //Station station1=stationService.selectStationList(station).get(0);
        SysUser sysUser = new SysUser();
        List<SysRole> list = roleService.list(new QueryWrapper<SysRole>().eq("role_name","员工"));
        String roleIds = list.stream().map(role -> String.valueOf(role.getRoleId())).collect(Collectors.joining(","));
        sysUser.setRoleId(roleIds);
        sysUser.setDeptId((long) 100);
        sysUser.setUserName(code);
        sysUser.setNickName(station.getStationName());
        sysUser.setUserLevel("2");
        sysUser.setAuthLevel("3");
        sysUser.setPhonenumber(station.getPhone());
        sysUser.setPassword(SecurityUtils.encryptPassword("123456"));
        sysUser.setStationId(station.getStationId());
        sysUser.setRoleIds(roles);
        if (StringUtils.equals("7", SecurityUtils.getLoginSysUser().getUserLevel())) {
            sysUser.setAuthorId(SecurityUtils.getLoginSysUser().getUserId());
            sysUser.setSupremeLevelName(SecurityUtils.getUsername());
        } else {
            SysUser byId = sysUserService.getById(SecurityUtils.getLoginSysUser().getUserId());
            sysUser.setAuthorId(byId.getAuthorId());
            SysUser aSysUser =  userMapper.selectUserById(SecurityUtils.getLoginSysUser().getUserId());
            if(aSysUser.getUserLevel()==null || aSysUser.getUserLevel().equals("7")){
                sysUser.setSupremeLevelName(aSysUser.getUserName());
            }else{
                sysUser.setSupremeLevelName(aSysUser.getSupremeLevelName());
            }
        }
        sysUser.setEnterpriseId(station.getEnterpriseId());
        int i = sysUserService.insertUser(sysUser);
        if (i <= 0) {
            return AjaxResult.error("新增失败");
        }
        return AjaxResult.success("新增油站成功", code);
    }

    /**
     * 修改油站信息
     *
     * @param station 油企信息
     * @return 结果
     */
    @CacheEvict(value = {"EnterpriseServiceImpl_selectStaInfoList"},
            key = "'e_' + #root.args[0].getEnterpriseId()",
            condition = "#root.args[0] != null"
    )
    public int updateStation(Station station) {
        station.setUpdatedTime(new Date());
        return stationMapper.updateStation(station);
    }

    /**
     * 删除油站信息
     *
     * @param stationId 油企信息ID
     * @return 结果
     */
    public int deleteStationById(Long stationId) {
        return stationMapper.deleteStationById(stationId);
    }

    /**
     * 批量删除油站信息
     *
     * @param stationIds 需要删除的数据ID
     * @return 结果
     */
    public int deleteStationByIds(Long[] stationIds) {
        return stationMapper.deleteStationByIds(stationIds);
    }

    @Override
    @Transactional
    public List<StationResVo> batchInsertStation(List<Station> stationList) throws Exception {
        ArrayList<StationResVo> stationResVoList = new ArrayList<>();
        for (Station station : stationList) {
            StationResVo stationResVo = new StationResVo();
            String stationName = station.getStationName();
            Station stationByName = stationService.selectStationByName(stationName);
            if (Objects.nonNull(stationByName)) {
                throw new CustomException("存在重复的油站名");
            }
            log.info("新增油站{}", station);
            int m = 0;
            Calendar cal = Calendar.getInstance();
            String regionData1 = "";
            String licenseImg = "";
            String ImgName = "";
            if (station.getRegionDataList() != null && station.getRegionDataList().length > 0) {
                for (String regionData : station.getRegionDataList()) {
                    if ("".equals(regionData1)) {
                        regionData1 += regionData;
                    } else {
                        regionData1 += "," + regionData;
                    }
                }

                if (!"".equals(regionData1)) {
                    station.setRegionData(regionData1);
                }
            }
            if (station.getImgFileList() != null && station.getImgFileList().size() > 0) {
                for (img img1 : station.getImgFileList()) {
                    if ("".equals(licenseImg)) {
                        licenseImg += img1.getUrl();
                        ImgName += img1.getName();
                    } else {
                        licenseImg += "," + img1.getUrl();
                        ImgName += "," + img1.getName();
                    }
                }

                if (!"".equals(licenseImg)) {
                    station.setImgUrl(licenseImg);
                    station.setImgName(ImgName);
                }
            }
            Random random = new Random();
            String result1 = "";
            for (int i = 0; i < 4; i++) {
                result1 += random.nextInt(10);
            }
            int year = cal.get(Calendar.YEAR);
            int month = cal.get(Calendar.MONTH) + 1;
            int yearcount = year - 2000;
            String code = "S" + yearcount + month + "0001" + result1;
            station.setStationCode(code);
            m = stationService.insertStation(station);
            if (m <= 0) {
                throw new CustomException("插入油站失败");
            }
            stationResVo.setStationCode(code);
            stationResVo.setStationName(station.getStationName());
            stationResVoList.add(stationResVo);
            Long[] roles = {Long.parseLong(19 + "")};
            //Station station1=stationService.selectStationList(station).get(0);
            SysUser sysUser = new SysUser();
            sysUser.setDeptId((long) 100);
            sysUser.setUserName(code);
            sysUser.setNickName(station.getStationName());
            sysUser.setUserLevel("2");
            sysUser.setPhonenumber(station.getPhone());
            sysUser.setPassword(SecurityUtils.encryptPassword("123456"));
            sysUser.setStationId(station.getStationId());
            sysUser.setRoleIds(roles);
            sysUser.setEnterpriseId(station.getEnterpriseId());
            sysUser.setAuthLevel("3");
            if (StringUtils.equals("7", SecurityUtils.getLoginSysUser().getUserLevel())) {
                sysUser.setAuthorId(SecurityUtils.getLoginSysUser().getUserId());
                sysUser.setSupremeLevelName(SecurityUtils.getUsername());
            } else {
                SysUser byId = sysUserService.getById(SecurityUtils.getLoginSysUser().getUserId());
                sysUser.setAuthorId(byId.getAuthorId());
                SysUser aSysUser =  userMapper.selectUserById(SecurityUtils.getLoginSysUser().getUserId());
                if(aSysUser.getUserLevel()==null || aSysUser.getUserLevel().equals("7")){
                    sysUser.setSupremeLevelName(aSysUser.getUserName());
                }else{
                    sysUser.setSupremeLevelName(aSysUser.getSupremeLevelName());
                }
            }
            sysUserService.insertUser(sysUser);

        }
        return stationResVoList;
    }
}
